{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def _get_ready_for_fit(df_train_x,df_train_y,window_size):\n",
    "    # Normalize\n",
    "    df_train_x = df_train_x/df_train_x.max()\n",
    "    df_train_y = df_train_y/df_train_x.max()\n",
    "    # Replace NaNs with 0s\n",
    "    df_train_x.fillna(0, inplace=True)\n",
    "    df_train_y.fillna(0,inplace=True)\n",
    "    # Find common parts of timeseries\n",
    "    ix = df_train_x.index.intersection(df_train_y.index)\n",
    "    # Move from Pandas to Numpy - the array/tensor format appreciated by Keras\n",
    "    np_train_x = np.array(df_train_x[ix])\n",
    "    np_train_y = np.array(df_train_y[ix])\n",
    "    # Create the indexer matrix\n",
    "    rows = np.arange(len(np_train_x) - window_size + 1).reshape(-1,1)\n",
    "    cols = np.arange(window_size).reshape(1,-1)\n",
    "    indexer = rows + cols\n",
    "    # Reshape the x training data into sliding windows.  Ending up with\n",
    "    # the number of rows staying as the number of readings and the columns\n",
    "    # ending up as the window_size. \n",
    "    np_train_x = np_train_x[indexer]\n",
    "    # Set the y training data to the midpoint of the device's column values\n",
    "    np_train_y = np_train_y[indexer]\n",
    "    midpoint = window_size // 2 - 1\n",
    "    np_train_y = np_train_y[:,midpoint]\n",
    "    # Get the data into the 3D tensor shape expected by model.fit\n",
    "\n",
    "    return np_train_x,np_train_y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "(355067, 100)\n(355067, 100, 1)\n"
     ]
    }
   ],
   "source": [
    "meters = ['microwave','fridge','dish washer','washer dryer']\n",
    "meter_key = meters[3]\n",
    "\n",
    "df_test_x = pd.read_pickle('created_data/REDD/test_main.pkl.zip')\n",
    "df_test_y = pd.read_pickle('created_data/REDD/test_{}.pkl.zip'.format(meter_key))\n",
    "\n",
    "\n",
    "test_x,test_y = _get_ready_for_fit(df_test_x,df_test_y,100)\n",
    "print(test_x.shape)\n",
    "\n",
    "test_x = np.reshape(test_x, (test_x.shape[0], test_x.shape[1], 1))\n",
    "print(test_x.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Model: \"sequential\"\n_________________________________________________________________\nLayer (type)                 Output Shape              Param #   \n=================================================================\nconv1d (Conv1D)              (None, 100, 30)           330       \n_________________________________________________________________\ndropout (Dropout)            (None, 100, 30)           0         \n_________________________________________________________________\nconv1d_1 (Conv1D)            (None, 100, 30)           7230      \n_________________________________________________________________\ndropout_1 (Dropout)          (None, 100, 30)           0         \n_________________________________________________________________\nconv1d_2 (Conv1D)            (None, 100, 40)           7240      \n_________________________________________________________________\ndropout_2 (Dropout)          (None, 100, 40)           0         \n_________________________________________________________________\nconv1d_3 (Conv1D)            (None, 100, 50)           10050     \n_________________________________________________________________\ndropout_3 (Dropout)          (None, 100, 50)           0         \n_________________________________________________________________\nconv1d_4 (Conv1D)            (None, 100, 50)           12550     \n_________________________________________________________________\ndropout_4 (Dropout)          (None, 100, 50)           0         \n_________________________________________________________________\nflatten (Flatten)            (None, 5000)              0         \n_________________________________________________________________\ndense (Dense)                (None, 1024)              5121024   \n_________________________________________________________________\ndropout_5 (Dropout)          (None, 1024)              0         \n_________________________________________________________________\ndense_1 (Dense)              (None, 1)                 1025      \n=================================================================\nTotal params: 5,159,449\nTrainable params: 5,159,449\nNon-trainable params: 0\n_________________________________________________________________\nNone\n"
     ]
    }
   ],
   "source": [
    "#load trained model\n",
    "model = tf.keras.models.load_model('washer dryer_seq2p_20201201_141223.h5')\n",
    "print(model.summary())\n",
    "#log file\n",
    "log = ''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "Final score (RMSE): 348.76788330078125\n"
     ]
    }
   ],
   "source": [
    "# @title Measure RMSE error...RMSE is common for regression.\n",
    "from sklearn import metrics\n",
    "pred = model.predict(test_x)\n",
    "score = np.sqrt(metrics.mean_squared_error(pred,test_y))\n",
    "print(f\"Final score (RMSE): {score}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "history = pd.read_csv('training__Sun Nov 29 20:46:14 2020.log')\n",
    "# history = pd.read_csv(log)\n",
    "# history.head()\n",
    "print(history.columns)\n",
    "# acc = history['accuracy']\n",
    "# val_acc = history['val_accuracy']\n",
    "acc = history['loss']\n",
    "val_acc = history['val_loss']\n",
    "epochs = history['epoch']\n",
    "\n",
    "plt.title('Training and Validation Accuracy')\n",
    "plt.plot(epochs,acc,color='blue',label='Train')\n",
    "plt.plot(epochs,val_acc,color='orange',label='Val')\n",
    "plt.xlabel('Epoch')\n",
    "plt.ylabel('Accuracy')\n",
    "plt.legend()\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "TimeSeriesSplit(max_train_size=4, n_splits=2)\nTRAIN: [0 1] TEST: [2 3]\nTRAIN: [0 1 2 3] TEST: [4 5]\n"
     ]
    }
   ],
   "source": [
    "from sklearn.model_selection import TimeSeriesSplit\n",
    "X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])\n",
    "y = np.array([1, 2, 3, 4, 5, 6])\n",
    "tscv = TimeSeriesSplit(max_train_size=4,n_splits=2)\n",
    "print(tscv)\n",
    "# TimeSeriesSplit(max_train_size=None, n_splits=2)\n",
    "for train_index, test_index in tscv.split(X):\n",
    "    print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n",
    "    X_train, X_test = X[train_index], X[test_index]\n",
    "    y_train, y_test = y[train_index], y[test_index]"
   ]
  }
 ]
}